﻿using Aspose.Pdf.Text;
using FastReport.DataVisualization.Charting;
using FastReport.Export.Pdf;
using FastReport.MSChart;
using FastReport;
using iText.Kernel.Pdf;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;
using QuestPDF.Previewer;

partial class Program
{
    static void TestPdfSharpReading()
    {
        var dir = @"D:\Users\Guoxudong\Documents\Developments\DaiDe\Projects\Core\zs3d-web-api\BackEndZS3\wwwroot\Reports";
        var files = Directory.GetFiles(dir, "ZSReport*New.pdf");
        var lines = PdfStreamContentsHelper.GetDefferentLines(files[0], files[1]);
        var perfect = PdfStreamContentsHelper.ReplaceLine(lines, files[0], files[0].Replace(".pdf", "_edit.pdf"));
    }
    static void TestFastReport()
    {
        var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        var templateFile = "练习.frx";
        var desktopFile = Path.Combine(desktop, templateFile);
        var exportFile = "report_test.pdf";
        //为了方便，可以将模板复制到桌面进行编辑，调试时会自动拷回来。
        if (File.Exists(desktopFile))
        {
            File.Copy(desktopFile, templateFile, true);
        }
        FastReportExport(templateFile, exportFile);
        if (File.Exists(desktopFile))
        {
            File.Copy(exportFile, Path.Combine(desktop, exportFile), true);
        }
    }
    static void FastReportExport(string templatePath, string exportFile)
    {
        using (Report report = new())
        {
            report.Load(templatePath);
            report.ReportInfo.Description = "报表信息文本";
            List<Contact> data =
            [
                new() { Id = "c1", Name = "张三", Age = 12, SchoolId = "s1", Extra = {MathsScore=20, EnglishScore=40 } },
                    new() { Id = "c2", Name = "李四", Age = 20, SchoolId = "s2", Extra = {MathsScore=24, EnglishScore=44 } },
                    new() { Id = "c3", Name = "王四", Age = 60, SchoolId = "s2", Extra = {MathsScore=28, EnglishScore=48 } }
            ];
            report.RegisterData(data, "Contact");
            report.SetParameterValue("MinAge", 1);
            List<School> data1 = [new School { Id = "s1", Name = "山西大学", Address = "山西太原" }, new School { Id = "s2", Name = "四川大学", Address = "四川成都" }];
            report.RegisterData(data1, "School1");
            report.Prepare();
            using PDFExport pdfExport = new();
            pdfExport.Export(report, exportFile);
        }
    }

    static void FastReportChartByCode()
    {
        MSChartObject MSChart1 = new MSChartObject();
        MSChart1.Width = 300;
        MSChart1.Height = 300;
        MSChart1.Chart.Legends.Add(new Legend() { Name = "Legend1", Title = "Legend title" });

        ChartArea chartArea1 = new ChartArea();
        chartArea1.Name = "ChartArea1";
        chartArea1.Axes[0].Title = "X name";
        chartArea1.Axes[1].Title = "Y name";
        MSChart1.Chart.ChartAreas.Add(chartArea1);

        Series series = new Series("sample");
        series.ChartType = SeriesChartType.Line;
        series.BorderWidth = 2;
        series.Points.Add(new DataPoint(0, 1));
        series.Points.Add(new DataPoint(1, 2));
        series.Points.Add(new DataPoint(3, 5));
        series.Points.Add(new DataPoint(4, 8));

        MSChart1.Chart.Series.Add(series);

        Report report = new Report();
        report.Load("ok.frx");
        DataBand db = report.FindObject("Data1") as DataBand;
        MSChart1.Parent = db;
    }
    static void TestQueryPdf()
    {
        QuestPDF.Settings.License = LicenseType.Community;
        var document = Document.Create(container =>
        {
            container.Page(page =>
            {
                page.Size(PageSizes.A4);
                page.Margin(2, Unit.Centimetre);
                page.PageColor(Colors.White);
                page.DefaultTextStyle(x => x.FontSize(20));

                page.Header()
                    .Text("Hello PDF!")
                    .SemiBold().FontSize(36).FontColor(Colors.Blue.Medium);

                page.Content()
                    .PaddingVertical(1, Unit.Centimetre)
                    .Column(x =>
                    {
                        x.Spacing(20);

                        x.Item().Text(Placeholders.LoremIpsum());
                        x.Item().Image(Placeholders.Image(200, 100));
                    });

                page.Footer()
                    .AlignCenter()
                    .Text(x =>
                    {
                        x.Span("Page ");
                        x.CurrentPageNumber();
                    });
            });
        });
        document.GeneratePdf("hello.pdf");
        // use the following invocation
        document.ShowInPreviewer();
    }

    // iTextPdf是收费软件，只能加载两页
    static void TestITextPdf(string filePath)
    {
        //BouncyCastleFactoryCreator.GetFactory().

        var dest = filePath.Replace(".pdf", "01.pdf");
        var writer1 = new PdfWriter(dest);
        var pdfDoc1 = new PdfDocument(writer1);
        pdfDoc1.AddNewPage();
        var document = new iText.Layout.Document(pdfDoc1);
        document.Close();

        var reader = new iText.Kernel.Pdf.PdfReader(filePath);
        var writer = new iText.Kernel.Pdf.PdfWriter(filePath.Replace(".pdf", "01.pdf"));
        var pdfDoc = new iText.Kernel.Pdf.PdfDocument(reader, writer);
        var doc = new iText.Layout.Document(pdfDoc);
        //pdfDoc.RemovePage(1);
        var page = pdfDoc.GetPage(2);
        //var text = PdfTextExtractor.GetTextFromPage(page);
        var all = page.GetPdfObject();
        var contents = all.GetAsStream(iText.Kernel.Pdf.PdfName.Contents);
        var resources = all.GetAsDictionary(iText.Kernel.Pdf.PdfName.Resources);

        var ba = contents.GetBytes();
        var s = Encoding.UTF8.GetString(ba);
        page.Remove(iText.Kernel.Pdf.PdfName.Contents);
        pdfDoc.RemovePage(1);
        doc.Close();
    }
    static void TestITextPdf2(string filePath)
    {
        var dir = @"D:\Users\Guoxudong\Documents\Developments\DaiDe\Projects\Core\zs3d-web-api\BackEndZS3\wwwroot\Reports";
        var files = Directory.GetFiles(dir, "ZSReport*New.pdf");
        foreach (var file in files)
        {
            var reader = new PdfReader(filePath);
            //var writer = new PdfWriter(filePath.Replace(".pdf", "01.pdf"));
            var pdfDoc = new PdfDocument(reader);
            var doc = new iText.Layout.Document(pdfDoc);

            var pageCount = pdfDoc.GetNumberOfPages();
            for (var i = 0; i < pageCount;)
            {
                var page = pdfDoc.GetPage(++i);
                var contentsCount = page.GetContentStreamCount();
                for (var j = 0; j < contentsCount; j++)
                {
                    var content = page.GetContentStream(j);
                    var bytes = content.GetBytes();
                    var str = Encoding.UTF8.GetString(bytes);
                    if (str.Contains("DEMO"))
                    {
                    }
                    //page.GetPdfObject().Put(PdfName.Contents, new PdfStream(Encoding.UTF8.GetBytes(s1)));
                }

            }
            doc.Close();

        }
    }


    //AsposePdf是收费软件，读可以，写不成功。
    static void TestAsposePdf(string filePath)
    {
        var doc = new Aspose.Pdf.Document(filePath);
        var page = doc.Pages[2];
        var a = page.HasVectorGraphics();
        var d = Path.GetDirectoryName(filePath);
        page.TrySaveVectorGraphics(Path.Combine(d, "abc.svg"));
        // Create TextAbsorber object to find all instances of the input search phrase
        TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("DEMO VERSION");

        // Accept the absorber for all the pages
        page.Accept(textFragmentAbsorber);
        // Get the extracted text fragments
        TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
        // Loop through the fragments
        foreach (TextFragment textFragment in textFragmentCollection)
        {
            // Update text and other properties
            textFragment.Text = "示例版本";
            textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue);
        }

        // Save resulting PDF document.
        doc.Save(filePath.Replace(".pdf", "01.pdf"));
    }

}
class Contact
{
    public string Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public int Age { get; set; }
    public string SchoolId { get; set; }
    public Extra Extra { get; private set; } = new Extra();

}
class Extra
{
    public int MathsScore { get; set; }
    public int EnglishScore { get; set; }
}
class School
{
    public string Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Address { get; set; } = string.Empty;
}

